<template>
	<div style="width: 100%">
		<div class="h-box-right mt-20">
			<div class="button-group">
				<div>
					<el-image class="mr-10" :src="goBottom" fit="fill"></el-image>
					<!--要件名-->
					<span>要件：{{ title || ' ' }}</span>
					<!--仅一次, 多次-->
					<span>（{{getDimTableItem({key:item.uploadLimit, dimTableList:dictionaries.itemUploadType}).value}}）</span>
					<!--关键要件  给员工用-->
					<el-tag
						v-if="showElement.showImDoc && transformationIsMvp(item.isMvp).show"
						class="ml-10"
						:type="transformationIsMvp(item.isMvp).type"
						:effect="transformationIsMvp(item.isMvp).effect">
						{{transformationIsMvp(item.isMvp).label}}
					</el-tag>
					<!--关键要件 及 风险要件:高中低  给领导用-->
					<!--没有被替换显示关键要件 且 这个是关键要件-->
					<el-tag
						v-if="showElement.showTagRiskImDoc && !isReplaceImDoc && transformationIsMvp(item.isMvp).show"
						class="ml-10"
						:type="transformationIsMvp(item.isMvp).type"
						:effect="transformationIsMvp(item.isMvp).effect">
						{{transformationIsMvp(item.isMvp).label}}
					</el-tag>
					<!--如果被替换了显示风险要件 且 这个是关键要件-->
					<el-tag
						v-if="showElement.showTagRiskImDoc && isReplaceImDoc && transformationIsMvp(item.isMvp).show"
						class="ml-10"
						:type="transformationIsMvp(item.isMvp).type"
						:effect="transformationIsMvp(item.isMvp).effect">
						{{transformationIsMvp(item.isMvp).name}}
					</el-tag>
				</div>

				<ul class="explain">
					<!--增加按钮置灰原因：-->
					<li class="tip-time" v-if="canAddItemDiscription">{{canAddItemDiscription}}</li>
				</ul>
				<el-button
					v-if="showElement.showBtnAdd && columns.length"
					type="primary"
					class="add-btn"
					:disabled="canAddItem"
					@click="handleAdd()"
				>增加
				</el-button>
			</div>
		</div>
		<div class="table-container" v-if="columns.length">
			<zk-table
				:columns="tableColumns"
				:service="service"
				style="width: 100%"
				codeKey="infoId"
				use-index
				:query="query"
				:use-pagination="false"
				:actions="actions"
				:height="height"
				:responseInterceptor="responseInterceptor"
				:request-interceptor="interceptor"
				@doOtherAction="doActions"
				@refresh-data="getRefreshData"
			>
				<template #control="scope">
					<el-button
						v-if="showElement.showBtnDown"
						size="small"
						type="text"
						@click="doActions({row:scope.row,type:'down'})">下载
					</el-button>
					<el-button
						v-if="showElement.showBtnDel"
						:disabled="disableBtn(scope)"
						size="small"
						type="text"
						@click="doActions({row:scope.row,type:'del'})">删除
					</el-button>
					<el-button
						v-if="showElement.showBtnSubstituteDescription"
						:disabled="disableBtn(scope)"
						size="small"
						type="text"
						@click="doActions({row:scope.row,type:'substituteDescription'})">替换说明
					</el-button>
				</template>
			</zk-table>
			<w-dialog :visible.sync="visible" height="auto" :title="modalTitle" width="600px" :id="itemId">
				<el-form ref="modelForm" :model="model" label-width="100px">
					<el-row>
						<el-col v-for="item of formColumns" :key="item.key" :span="item.span || 20" :offset="2">
							<el-form-item
								:label="item.label"
								:prop="item.key"
								:rules="item.required && [{ required: true, message: `请输入${item.label}`, trigger: ['blur'] }]"
							>
								<zk-item-pool
									v-model="model[item.key]"
									:option="{...item, disabled:item.disabled }"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="20" :offset="3">
							<el-upload
								style="padding:10px 0;"
								ref="upload"
								action="/moon/rest/file/upload"
								:auto-upload="true"
								:limit="limit"
								:file-list="fileList"
								:on-preview="handlePreview"
								:on-remove="handleRemove"
								:on-exceed="handleExceed"
								:on-success="handleSuccess"
								:on-error="handleError"
							>
								<el-button slot="trigger" size="small" type="primary">上传要件</el-button>
								<div slot="tip" class="el-upload__tip">可以上传图片、PDF、压缩文件等</div>
							</el-upload>
						</el-col>
					</el-row>
				</el-form>
				<template #footer>
					<div class="flex-end">
						<el-button type="default" @click="cancel">取 消</el-button>
						<el-button type="primary" @click="submit">保 存</el-button>
					</div>
				</template>
			</w-dialog>

			<!--请输入替换说明-->
			<w-dialog :visible.sync="visibleSubstituteDescription" height="auto" title="替换说明" width="600px">
				<el-input
					type="textarea"
					:rows="10"
					placeholder="请输入替换说明"
					v-model="textareaSubstituteDescription">
				</el-input>
				<template #footer>
					<div class="flex-end">
						<el-button type="default" @click="cancelSubstituteDescription">取 消</el-button>
						<el-button type="primary" @click="submitSubstituteDescription">确 定</el-button>
					</div>
				</template>
			</w-dialog>


		</div>
	</div>
</template>
<script>
import { mapGetters }          from 'vuex'
import goBottom                from '@/assets/images/go-bottom.png'
import { itemInfo as service } from '@/services'
import SearchTableCRUDMixin    from '@/mixins/search-table-crud-mixin'
import _                       from 'lodash'
import { getDimTableItem }     from '@/utils/index.js'

export default {
	mixins  : [SearchTableCRUDMixin],
	props   : {
		showElement: {
			type   : Object,
			default: () => ({
				showImDoc                   : true, //关键要件
				showTagRiskImDoc            : false,//风险要件
				showBtnAdd                  : true, //增加按钮
				showBtnDown                 : true, //下载按钮
				showBtnDel                  : true, //删除按钮
				showBtnSubstituteDescription: true, //替换说明按钮
			})
		},
		item       : {
			type   : Object,
			default: () => ({})
		},
		title      : {
			type   : String,
			default: ''
		},
		taskId     : {
			type   : Number,
			default: null
		},
		itemId     : {
			type   : Number,
			default: null
		}
	},
	data() {
		return {
			projectId                    : this.$route.params.id,
			goBottom,
			columns                      : [],
			service,
			isReplaceImDoc               : false,//是替换要件
			tableData                    : [],
			actions                      : ['slot', 200],
			height                       : 100, //table 高度
			//替代说明
			visibleSubstituteDescription : false,
			textareaSubstituteDescription: '',
			//
			limit                        : 1,
			fileList                     : [],  // [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]
			fileIdList                   : [], //[22,33,44,98]
		}
	},
	computed: {
		...mapGetters(['selectedTask', 'dictionaries']),
		modalTitle() {
			return this.isAddModal ? '添加' : '编辑'
		},
		columnTypeMapping() {
			const { colType } = this.dictionaries
			return _.groupBy(colType, 'key')
		},
		//增加按钮 disabled
		canAddItem() {
			if (this.selectedTask.status == '01') return true; //任务未开始, 不可以增加
			if (this.selectedTask.spFlag == '0') return true; //任务正在审批, 不可以增加
			if (this.item.uploadLimit == '01' && this.tableData.length) return true;// 要件信息上报方式为:仅一次 && 表格已经有数据了 不可以增加
		},
		canAddItemDiscription() {
			if (this.selectedTask.status == '01') return '增加按钮置灰原因：任务未开始'; //任务未开始, 不可以增加
			if (this.selectedTask.spFlag == '0') return '增加按钮置灰原因：任务正在审批'; //任务正在审批, 不可以增加
			if (this.item.uploadLimit == '01' && this.tableData.length) return '增加按钮置灰原因：要件信息上报方式为仅一次 且 表格已经有数据了';// 要件信息上报方式为:仅一次 && 表格已经有数据了 不可以增加
			return ''
		}
	},
	watch   : {
		itemId(newValue) {
			console.log('watch itemId wgm'); //不会触发
			this.getColumnsAndData(newValue)
		},
		columns(newValue) {},
		fileList(nVal, oVal) {
			console.log('watch fileList', nVal, oVal);
		}
	},
	methods : {
		getDimTableItem,
		disableBtn(scope) {
			/*
			{key: null, value: '任务未提交'},
		  {key: '0', value: '任务正在审批'},
		  {key: '1', value: '任务完成'},
		  {key: '2', value: '任务被驳回'},
			*/
			if (scope.row.spFlag == null) { return false }
			if (scope.row.spFlag == '0') { return true }
			if (scope.row.spFlag == '1') { return true }
			if (scope.row.spFlag == '2') { return false }

		},
		// item.isMvp
		transformationIsMvp(key) {
			return this.dictionaries.itemImportantDocument.find(item => item.key == key)
		},
		getRefreshData({ tableData }) {
			this.tableData = tableData;
			if (!this.tableData.length) this.$store.commit('setState', {
				disableTaskBtn: true
			})
			this.isReplaceImDoc = this.tableData.some(item => item['是否替换'] === '是')
		},
		async submit() {
			this.$refs.modelForm.validate(async (valid) => {
				if (valid) {
					if (!this.fileIdList.length) {
						this.$message.warning(`请上传要件`);
						return;
					}
					const body = {
						...this.model,
						"prjId"     : +this.projectId,
						"workId"    : this.selectedTask.rtaProTaskInfo.relWorkId,
						"taskId"    : +this.selectedTask.taskPzId,
						"itemId"    : +this.itemId,
						"fileIdList": this.fileIdList,
					}
					if (this.isAddModal) {
						delete body.id
						await this.service.addItem(body);
						this.$emit('task-refresh', this.selectedTask);
					}
					else {
						await this.service.editItem(body) && this.reload()
					}
					this.cancel();
				}
			})
		},
		cancel() {
			this.model = {}
			this.fileList = [];
			this.fileIdList = [];
			this.visible = false
		},
		async doActions({ row, type }) {
			if (type === 'down') {
				window.open(`/moon/rest/file/download?fileid=${ row.fileIdList[0].fileId }`)
			}
			else if (type === 'edit') {
				this.isAddModal = false
				this.model = { ...row }
				this.visible = true
			}
			else if (type === 'del') {
				this.model = { ...row }
				this.$alert(`确认删除此条要件记录?`, '确认删除', {
					confirmButtonText: '确定',
					callback         : async action => {
						if (action === 'confirm') {
							const result = await this.service.delItem(this.projectId, row.infoId)
							if (result) {
								await this.reload()
								this.$message.success(`删除成功`)
							}
							else {
								this.$message.warning(`删除失败`)
							}
						}
						this.model = {};
					}
				})
			}
			else if (type === 'substituteDescription') {
				console.log('substituteDescription', row);
				this.visibleSubstituteDescription = true;
				this.model = { ...row };
			}
		},
		async getColumnsAndData(id) {
			if (!id) {
				console.error('没传id');
				return;
			}
			// 一共有两次请求, getItemColumns 和 getList 其中 getItemColumns 封在 zk-table 里面了
			// 这个列头是动态的传过来的, 后台用的是 mongodb
			const columns = await service.getItemColumns(id) // GET /moon/rest/info/searchItemColList?itemId=41
			this.columns = columns.map(e => {
				// console.log('e', e);

				/*this.columns = [
					{key: "会议时间", label: "会议时间", required: true, type: "DATE_TIME"},
					{key: "参会人员", label: "参会人员", required: true, type: "INPUT"},
					{key: "参会人员", label: "参会人员", required: true, type: "INPUT"},
					{key: "附件数量", label: "附件数量", required: true, type: undefined},
					{key: "完成人",   label: "完成人", required: true, type: undefined},
					{key: "完成部门", label: "完成部门", required: true, type: undefined},
					{key: "完成时间", label: "完成时间", required: true, type: undefined},
				]*/

				if (
					["附件数量", "完成人", "完成部门", "完成时间", "替换说明"].includes(e['colName'])
				) {
					return {
						label   : e['colName'],
						key     : e['colName'],
						// type    : 'INPUT',
						required: false,
						table   : true,
						form    : false
					}
				}

				if (
					["是否替换"].includes(e['colName'])
				) {
					return {
						label   : e['colName'],
						key     : e['colName'],
						// type    : 'INPUT',
						storeKey: "yesNo",
						required: false,
						table   : true,
						form    : false
					}
				}

				return {
					label   : e['colName'],
					key     : e['colName'],
					type    : (this.columnTypeMapping[e.colType] || [{}])[0].mapping,//INPUT NUMBER DATE DATE_TIME
					// type: (this.columnTypeMapping['05'] || [{}])[0].mapping,
					required: true,
					table   : true,
					form    : true
				}
			})

			// console.log('this.columns', this.columns);
		},
		interceptor() {
			return {
				"prjId" : this.projectId,
				"taskId": this.selectedTask.taskPzId,
				"workId": this.selectedTask.rtaProTaskInfo.relWorkId,
				"itemId": this.itemId,
			}
		},
		responseInterceptor(list = []) {
			this.height = 56 * (list.length + 1)
			return list
		},
		//
		async submitSubstituteDescription() {
			if (!this.textareaSubstituteDescription) {
				this.$message.warning(`替换说明不能为空!`)
				return
			}
			const { prjId, infoId } = this.model;
			const result = await service.repleaseItemInfo({
				prjId,
				infoId,
				"msg": this.textareaSubstituteDescription
			})
			console.log('result', result);
			if (result.code == 0) {
				this.visibleSubstituteDescription = false;
				this.textareaSubstituteDescription = '';
				this.$message.success(`替换说明提交成功`)
				this.reload();
			}
			else {
				this.$message.warning(`替换说明提交失败`)
			}
		},
		cancelSubstituteDescription() {
			this.visibleSubstituteDescription = false;
			this.textareaSubstituteDescription = '';
		},
		// upLoad 部分
		handleRemove(file, fileList) {
			console.log(file, fileList);
		},
		handlePreview(file) {
			console.log(file);
		},
		handleExceed(files, fileList) {
			this.$message.warning(`最多上传 ${ this.limit } 个文件，本次选择了 ${ files.length } 个文件，共选择了 ${ files.length + fileList.length } 个文件`);
			console.log('this.fileList', this.fileList, fileList);
		},
		beforeRemove(file, fileList) {
			return this.$confirm(`确定移除 ${ file.name }？`);
		},
		submitUpload() {
			this.$refs.upload.submit();
			console.log('this.fileList', this.fileList);
		},
		handleSuccess(response, file, fileList) {
			console.log(response, file, fileList);
			if (response.code != 0) return;
			this.fileIdList = [response.data.payload.fileId]
		},
		handleError(err, file, fileList) {
			console.log(err, file, fileList);
			this.$message.warning(`上传要件失败!`)
		}
	},
	mounted() {
		// console.log('mounted wgm', this.itemId); //为什么会多触发1次??
		this.getColumnsAndData(this.itemId)
	},
}
</script>
<style scoped lang="scss">
	@import "~@/assets/css/_variables.scss";

	.button-group {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 4px;
		width: 96%;
	}

	.table-container {
		display: block;
		width: 96%;
	}

	.explain {
		@include flex-start();
		flex-wrap: wrap;

		.tip-time {
			width: fit-content;
			min-width: fit-content;
			font-size: 12px;
			line-height: 18px;
			margin-right: 30px;
		}
	}
</style>
